/**
 * 公共方法集合
 * @Date 2021/06/12
 * @Author Ghc
*/

const hasOwnProperty = Object.prototype.hasOwnProperty
export const hasOwn = (
    val: Object,
    key: string | symbol
): key is keyof typeof val => hasOwnProperty.call(val, key)

/**
 * 类型检测
 */
export const isArray = Array.isArray
export const isMap = (val: unknown): val is Map<any, any> => toTypeString(val) === '[object Map]'
export const isSet = (val: unknown): val is Set<any> => toTypeString(val) === '[object Set]'

export const isDate = (val: unknown): val is Date => val instanceof Date
export const isFunction = (val: unknown): val is Function => typeof val === 'function'
export const isString = (val: unknown): val is string => typeof val === 'string'
export const isSymbol = (val: unknown): val is symbol => typeof val === 'symbol'
export const isObject = (val: unknown): val is Record<any, any> => val !== null && typeof val === 'object'

export const isPromise = <T = any>(val: unknown): val is Promise<T> => {
  return isObject(val) && isFunction(val.then) && isFunction(val.catch)
}

export const objectToString = Object.prototype.toString
export const toTypeString = (value: unknown): string => objectToString.call(value)

export const toRawType = (value: unknown): string => {
  return toTypeString(value).slice(8, -1)
}

export const isPlainObject = (val: unknown): val is object => toTypeString(val) === '[object Object]'

/**
 * 常用正则校验
 */
export const isPhone = (val: string): boolean => {
  return /^1[2,3,4,5,7,8]\d{9}$/.test(val)
}
export const isEmail = (val: string): boolean => {
  return /^[A-Za-z\d]+[A-Za-z\d\-_.]*@([A-Za-z\d]+[A-Za-z\d-]*\.)+[A-Za-z]{2,4}$/.test(val)
}
export const isCard = (val: string): boolean => {
  return /^((\d{18})|([0-9x]{18})|([0-9X]{18}))$/.test(val)
}

/**
 * 根据需要的格式获取当前系统时间
 * @param fmt
 * @returns String 当前系统格式化后的时间
 */
export const getSystemTime = (fmt: string): string => {
  fmt = fmt || 'yyyy-MM-dd HH:mm:ss'
  const dateTime = new Date()
  const o = {
    'M+': dateTime.getMonth() + 1, // 月份
    'd+': dateTime.getDate(), // 日
    'H+': dateTime.getHours(), // 小时
    'm+': dateTime.getMinutes(), // 分
    's+': dateTime.getSeconds(), // 秒
    'q+': Math.floor((dateTime.getMonth() + 3) / 3), // 季度
    'S': dateTime.getMilliseconds() // 毫秒
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (dateTime.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  for (const k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      // @ts-ignore
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
    }
  }
  return fmt
}

/**
 * 日期格式化
 * @param time
 * @param pattern
 */
export function parseTime(time: any, pattern: string): any {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    } else if (typeof time === 'string') {
      time = time.replace(new RegExp(/-/gm), '/')
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  return format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    // @ts-ignore
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
}

/**
 * @param method 需要执行类型
 * @param name 缓存中的数据名称
 * @param obj
 * @returns {any}
 */
export const publicActionSessionStorage = (method: string, name: string, obj?: string) => {
  switch (method) {
    case 'get':
      if (sessionStorage.getItem(name + '_obj')) {
        return JSON.parse(<string>sessionStorage.getItem(name + '_obj'))
      } else if (sessionStorage.getItem(name + '_str')) {
        return sessionStorage.getItem(name + '_str')
      } else {
        return false
      }
    case 'set':
      publicActionSessionStorage('clean', name)
      if (typeof obj === 'object') {
        sessionStorage.setItem(name + '_obj', JSON.stringify(obj))
      } else {
        if (typeof obj === "string") {
          sessionStorage.setItem(name + '_str', obj)
        }
      }
      return true
    case 'clean':
      sessionStorage.removeItem(name + '_obj')
      sessionStorage.removeItem(name + '_str')
      return true
  }
}

/**
 * 回显数据字典
 * @param datas
 * @param value
 */
export function selectDictLabel(datas: any, value: any) {
  const actions: any[] = []
  Object.keys(datas).some((key) => {
    if (datas[key].dictValue == ('' + value)) {
      actions.push(datas[key].dictLabel)
      return true
    }
  })
  return actions.join('')
}

/**
 * 回显数据字典（字符串数组）
 * @param datas
 * @param value
 * @param separator
 */
export function selectDictLabels(datas: any, value: any, separator: any) {
  const actions: any[] = []
  const currentSeparator = undefined === separator ? ',' : separator
  const temp = value.split(currentSeparator)
  Object.keys(value.split(currentSeparator)).some((val) => {
    Object.keys(datas).some((key) => {
      if (datas[key].dictValue == ('' + temp[val])) {
        actions.push(datas[key].dictLabel + currentSeparator)
      }
    })
  })
  return actions.join('').substring(0, actions.join('').length - 1)
}

// 转换字符串，undefined,null等转化为""
export function praseStrEmpty(str: string | [string, number]) {
  if (!str || str == 'undefined' || str == 'null') {
    return ''
  }
  return str
}
